# -*- coding:utf-8 -*-

"""
    操作config.ini文件
"""

import os
import ConfigParser


class Config:
    def __init__(self, path="config.ini"):
        self.path = path
        self.cf = ConfigParser.ConfigParser()
        self.initialize_ini()
        # self.cf.open(self.path, "w+")
        self.cf.read(self.path)

    def get(self, field, key):
        try:
            result = self.cf.get(field, key)
        except Exception as e:
            print "get config item fail:", e
            result = ""
        return result

    def set(self, field, key, value):
        try:
            self.cf.set(field, key, value)
            self.cf.write(open(self.path, 'w'))
        except Exception as e:
            print "set config item fail:", e
            return False
        return True

    def initialize_ini(self):
        """如果文件不存在则创建默认配置的文件，或提示出错"""
        if not os.path.exists(self.path):
            "设置section段及对应的值"
            cf = ConfigParser.ConfigParser()

            "path，脚本/工具的路径配置"
            cf.add_section("path")
            cf.set("path", "workspace", "")  # 工作空间，如截图、logs目录存放的地方，默认为脚本/工具所在的路径
            cf.set("path", "apk_dir_extend", "e:\\apk,")  # 本地apk目录，可以实现打开多个apk目录进行安装

            "url相关，主要用于打包平台"
            cf.add_section("url")
            cf.set("url", "ppcenter", "http://100.84.35.78:49000")  # 打包平台的地址

            "写入文件"
            cf.write(open(self.path, "w"))

    @staticmethod
    def read_config(config_file_path, field, key):
        cf = ConfigParser.ConfigParser()
        try:
            cf.read(config_file_path)
            result = cf.get(field, key)
        except Exception as e:
            print "read config file fail:", e
            result = ""
        return result

    def read_path_config(self, field, key):
        cf = ConfigParser.ConfigParser()
        try:
            cf.read(self.path)
            result = cf.get(field, key)
            if result.startswith("\\"):
                result = result[1:]
            if not result.endswith("\\"):
                result += "\\"
        except Exception as e:
            print "read path from config file fail:", e
            result = ""
        return result

    @staticmethod
    def write_config(config_file_path, field, key, value):
        cf = ConfigParser.ConfigParser()
        try:
            cf.read(config_file_path)
            cf.set(field, key, value)
            cf.write(open(config_file_path, 'w'))
        except Exception as e:
            print "write config file fail:", e
            return False
        return True

    @staticmethod
    def get_workspace():
        path_str = Config().read_path_config("path", "workspace")
        if len(path_str) > 1 and os.path.exists(path_str):
            path = path_str
        else:
            path = os.getcwd()+"\\"
        return path

if __name__ == "__main__":
    pass
